package com.kymatrix.kycarbon.xsmd.common.business.common;

import com.kymatrix.kycarbon.xsmd.common.constants.Constant;
import com.kymatrix.kycarbon.xsmd.common.springboot.util.SpringContextUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import lombok.Data;

@Data
@ApiModel(value = "接口返回对象")
public class ResultResp<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功标志
     */
    @ApiModelProperty(value = "成功标志")
    private boolean success = true;

    /**
     * 返回处理消息
     */
    @ApiModelProperty(value = "返回处理消息")
    private String message = "";

    /**
     * 返回代码
     */
    @ApiModelProperty(value = "返回代码")
    private Integer code = 0;

    /**
     * 返回数据对象 data
     */
    @ApiModelProperty(value = "返回数据对象")
    private transient T result;

    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳")
    private long timestamp = System.currentTimeMillis();

    private ResultResp() {

    }

    /**
     * ok
     */
    public static <T> ResultResp<T> ok() {
        return ok(Constant.SUCCESS);
    }

    /**
     * ok
     */
    public static <T> ResultResp<T> ok(String msg) {
        return ok(null, msg);
    }

    /**
     * ok
     */
    public static <T> ResultResp<T> ok(T data) {
        return ok(data, null);
    }
    
    private static <T> ResultResp<T> ok(T data, String msg) {
        ResultResp<T> r = new ResultResp<>();
        r.setSuccess(true);
        r.setMessage(msg);
        r.setCode(Constant.SC_OK_200);
        r.setResult(data);
        return r;
    }



    /**
     * error
     */
    public static <T> ResultResp<T> error(String msg, T data) {
        return error(Constant.SC_INTERNAL_SERVER_ERROR_500, msg, data);
    }

    public static <T> ResultResp<T> error(int code, String message) {
        return error(code, message, null);
    }

    /**
     * error
     */
    public static <T> ResultResp<T> error(String msg) {
        return error(Constant.SC_INTERNAL_SERVER_ERROR_500, msg, null);
    }

    public static <T> ResultResp<T> authError(String msg) {
        return error(Constant.SC_UNAUTHORIZED_ERROR_401, msg, null);
    }

    /**
     * error
     */
    private static <T> ResultResp<T> error(int code, String msg, T data) {
        ResultResp<T> r = new ResultResp<>();
        r.setCode(code);
        r.setMessage(msg);
        r.setSuccess(false);
        r.setResult(data);
        SpringContextUtil.getHttpServletResponse().setStatus(code);
        return r;
    }

}
